//
//  QZAddressController.m
//  WeiWeiHaircut
//
//  Created by 超群 on 15/10/16.
//  Copyright © 2015年 超群. All rights reserved.
//

#import "QZAddressController.h"
#import "QZAddressCell.h"
#import "QZAddressViewController.h"
#import "QZAddressModel.h"
#import "MJRefresh.h"
@interface QZAddressController ()<UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *mainView;

@property (strong, nonatomic) NSMutableArray *addressS;

@property (strong,nonatomic) QZAddressModel *selectMidel;//修改默认地址时候使用的

@end

@implementation QZAddressController{
    /** 翻页数 */
    NSInteger _page;
}

-(NSMutableArray *)addressS{
    if (!_addressS) {
        _addressS = [NSMutableArray array];
    }
    return _addressS;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    _page = 1;
    
    [self downloadAddress];
    
}
/**
 * 下拉刷新
 */
-(void)addaRefresh{
    self.mainView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _page = 1;
        [self downloadAddress];
        [self.mainView.header endRefreshing];
    }];
    
    self.mainView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page ++;
        [self downloadAddress];
        [self.mainView.footer endRefreshing];
    }];
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"收货地址";

    [self addBtnOnNavWithTitle:@"我" andImageName:@"返回" andTarget:self andAction:@selector(backAction) andFrame:CGRectMake(0, 0, 30, 20) andDirection:left];
    
    [self addaRefresh];
    
    [self prepareUI];
}
-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)prepareUI{
    _mainView.separatorStyle = NO;
    [_mainView registerNib:[UINib nibWithNibName:@"QZAddressCell" bundle:nil] forCellReuseIdentifier:@"QZAddressCell"];
    self.automaticallyAdjustsScrollViewInsets = NO;
}
#pragma mark tableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    QZAddressModel *model = self.addressS[indexPath.section];
    if (_changeAddress) {
        _changeAddress(model);
        [self.navigationController popViewControllerAnimated:YES];
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.addressS.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    QZAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QZAddressCell" forIndexPath:indexPath];
    QZAddressModel *model = self.addressS[indexPath.section];
    cell.addressModel = model;
    __weak typeof(self) weakSelf = self;
    cell.blick = ^(UIButton *btn){
        weakSelf.selectMidel = model;
        NSString *string = [NSString stringWithFormat:@"%@%@",newPublicURL,@"Address.GetAddressDefalut"];
        
        NSDictionary *dic = @{
                              @"address_id":@(model.id),
                              @"user_id":[QZUserInfo userId]
                              };
        [weakSelf.request QZRequest_POST:string parameters:dic tagNSString:@"设置默认地址" stopRequest:YES isSerializer:NO isCache:YES];
        
        
    };
        
    
    
    //编辑点击事件
    if (!cell.changeAddressVImageView.gestureRecognizers) {
        cell.changeAddressVImageView.tag = 100 + indexPath.section;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeAddressVImageViewClick:)];
        [cell.changeAddressVImageView addGestureRecognizer:tap];
    }
    
    return cell;

}

#pragma mark 编辑address
-(void)changeAddressVImageViewClick:(UITapGestureRecognizer *)tap{
    
    QZAddressModel *model = self.addressS[tap.view.tag - 100];
    
    QZAddressViewController *addAddress = [[QZAddressViewController alloc] initWithNibName:nil bundle:nil];
    addAddress.isChangeAddress = YES;
    addAddress.addressModel = model;
    addAddress.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:addAddress animated:YES];
    
}
- (IBAction)addAddress:(id)sender {
    
    QZAddressViewController *addAddress = [[QZAddressViewController alloc] initWithNibName:nil bundle:nil];
    
    addAddress.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:addAddress animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 90;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.000001;
}

#pragma mark cell的 删除
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    

    QZAddressModel *model = self.addressS[indexPath.section];
    
    [self.addressS removeObject:self.addressS[indexPath.section]];
    
    [self.mainView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationRight];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"Address.GetAddressDel"];
    
    
    NSDictionary *dic= @{
                         @"address_id":@(model.id)
                         };
    
    self.request.isShowHUD = NO;
    [self.request QZRequest_POST:url parameters:dic tagNSString:@"删除地址" stopRequest:YES isSerializer:NO isCache:NO];
    
    
    
}

-(void)downloadAddress{
    NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"Address.GetAddressList"];
    if (self.addressS.count>0) {
        self.request.isShowHUD = NO;
    }
    [self.request QZRequest_POST:url parameters:@{@"user_id":[QZUserInfo userId],@"page":@(_page),@"limit":@(5)} tagNSString:@"地址列表" stopRequest:YES isSerializer:NO isCache:YES];

    
}
-(void)request_POST_FinishValue:(id)value tagNSString:(NSString *)tag{
    
    if ([tag isEqualToString:@"地址列表"]) {
        if ([value[@"data"][@"status"] integerValue] == 100) {
            NSLog(@"%ld",_page);
            if (_page == 1) {
                [self.addressS removeAllObjects];
            }
            NSArray *addresss = value[@"data"][@"data"][@"list"];
            
            if ([addresss isKindOfClass:[NSNull class]]) {
                [[iToast makeText:@"没有地址信息"] show];
                return;
            }
            
            for (NSDictionary *dic in addresss) {
                QZAddressModel *model = [[QZAddressModel alloc] initWithDictionary:dic error:nil];
                
                [self.addressS addObject:model];
                
                [self.mainView reloadData];
            }
            
        }
        
    }
    
    
    if ([tag isEqualToString:@"删除地址"]) {
        if ([value[@"data"][@"status"] integerValue] == 100) {
            
            NSLog(@"%@",value);
        }
        NSLog(@"%@",value);
    }
    
    if ([tag isEqualToString:@"设置默认地址"]) {
        if ([value[@"data"][@"status"] integerValue] == 100) {
            for (int i = 0; i< self.addressS.count; i++) {
                QZAddressModel *model =self.addressS[i];
                if (self.selectMidel == model) {
                    model.isDefault = 0;
                   
                }else{
                    model.isDefault = 1;
                }
            }
            
            [self.mainView reloadData];
        }
        
    }
  
}

@end
